package com.yuyang.wifi.views;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdManager;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTFullScreenVideoAd;
import com.yuyang.wifi.MyApplication;

import static com.bun.miitmdid.content.ContextKeeper.getApplicationContext;

/**
 * created by mej
 * on 2020/12/2
 */
public class LoadCsjNewInsertFullExtAdUtils {

    private Context mContext;
    private TTAdNative mTTAdNative;
    private OnItemAllClickListener onItemAllClickListener;
    private OnItemCompleteListener onItemAllCompleteListener;
    private OnLoadFailureListener onLoadFailureListener;

    static LoadCsjNewInsertFullExtAdUtils instance = new LoadCsjNewInsertFullExtAdUtils();
    private String mInsertAdId;
    private boolean mIsExpress = false; //是否请求模板广告
    private boolean mIsLoaded = false; //视频是否加载完成
    private static final String TAG = "FullScreenVideoActivity";
    private TTFullScreenVideoAd mttFullVideoAd;
    private int adLoadCount;
    private TTAdManager ttAdManager;

    public static LoadCsjNewInsertFullExtAdUtils getInstance() {
        return instance;
    }

    //一、加载穿山甲激励视频
    //BDAdvanceBaseAppNative 绑定激励视频回调
    public void load(final Context context, String moduleName) {
        adLoadCount = 0;
        mIsLoaded = false;
        mContext = context;
        mInsertAdId = MyApplication.getCsjAdIdChannel(moduleName);
        initAdAppId3();
        loadAd();
    }

    private void initAdAppId3() {
        //step1:初始化sdk
        if (ttAdManager == null) {
            ttAdManager = TTAdManagerHolder.get();
        }
        //step2:(可选，强烈建议在合适的时机调用):申请部分权限，如read_phone_state,防止获取不了imei时候，下载类广告没有填充的问题。
        TTAdManagerHolder.get().requestPermissionIfNecessary(mContext);
        //step3:创建TTAdNative对象,用于调用广告请求接口
        if (mTTAdNative == null) {
            mTTAdNative = ttAdManager.createAdNative(getApplicationContext());
        }

    }

    private boolean mHasShowDownloadActive = false;

    @SuppressWarnings("SameParameterValue")
    private void loadAd() {
        //step4:创建广告请求参数AdSlot,具体参数含义参考文档
        AdSlot adSlot;
        if (mIsExpress) {
            adSlot = new AdSlot.Builder()
                    .setCodeId(mInsertAdId)
                    //模板广告需要设置期望个性化模板广告的大小,单位dp,全屏视频场景，只要设置的值大于0即可
                    .setExpressViewAcceptedSize(500, 500)
                    .build();

        } else {
            adSlot = new AdSlot.Builder()
                    .setCodeId(mInsertAdId)
                    .build();
        }
        //step5:请求广告
        mTTAdNative.loadFullScreenVideoAd(adSlot, new TTAdNative.FullScreenVideoAdListener() {
            @Override
            public void onError(int code, String message) {
                Log.i("csj_ad", "insertFull_onError, adError========" + message);
                if (adLoadCount < 15) {
                    adLoadCount++;
                    loadAd();
                } else {
                    if (null != handlerLooper) {
                        handlerLooper.removeCallbacksAndMessages(null);
                    }

                    if (null != onLoadFailureListener) {
                        onLoadFailureListener.onLoadFailureListener();
                    }
                }
                Log.e(TAG, "Callback --> onError: " + code + ", " + String.valueOf(message));
                // loadAd();
                //错误的回调
                Log.e("ss", "onLoadFailureListener:==ylh转csj4444");

            }

            @Override
            public void onFullScreenVideoAdLoad(TTFullScreenVideoAd ad) {
                Log.e(TAG, "Callback --> onFullScreenVideoAdLoad");
                mttFullVideoAd = ad;
                mIsLoaded = false;
                mttFullVideoAd.setFullScreenVideoAdInteractionListener(new TTFullScreenVideoAd.FullScreenVideoAdInteractionListener() {

                    @Override
                    public void onAdShow() {
                        Log.d(TAG, "Callback --> FullVideoAd show");
                        //TToast.show(FullScreenVideoActivity.this, "FullVideoAd show");
                    }

                    @Override
                    public void onAdVideoBarClick() {
                        Log.d(TAG, "Callback --> FullVideoAd bar click");
                        //TToast.show(FullScreenVideoActivity.this, "FullVideoAd bar click");
                    }

                    @Override
                    public void onAdClose() {
                        loadAd();
                        Log.d(TAG, "Callback --> FullVideoAd close");
                        //TToast.show(FullScreenVideoActivity.this, "FullVideoAd close");
                        if (null != onItemAllClickListener) {
                            onItemAllClickListener.onItemAllClickListener();
                        }
                    }

                    @Override
                    public void onVideoComplete() {
                        Log.d(TAG, "Callback --> FullVideoAd complete");
                        //TToast.show(FullScreenVideoActivity.this, "FullVideoAd complete");
                        if (null != onItemAllCompleteListener) {
                            onItemAllCompleteListener.onItemCompleteListener();
                        }
                    }

                    @Override
                    public void onSkippedVideo() {
                        Log.d(TAG, "Callback --> FullVideoAd skipped");
                        //TToast.show(FullScreenVideoActivity.this, "FullVideoAd skipped");

                    }

                });


                ad.setDownloadListener(new TTAppDownloadListener() {
                    @Override
                    public void onIdle() {
                        mHasShowDownloadActive = false;
                    }

                    @Override
                    public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
                        Log.d("DML", "onDownloadActive==totalBytes=" + totalBytes + ",currBytes=" + currBytes + ",fileName=" + fileName + ",appName=" + appName);

                        if (!mHasShowDownloadActive) {
                            mHasShowDownloadActive = true;
                            //TToast.show(FullScreenVideoActivity.this, "下载中，点击下载区域暂停", Toast.LENGTH_LONG);
                        }
                    }

                    @Override
                    public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
                        Log.d("DML", "onDownloadPaused===totalBytes=" + totalBytes + ",currBytes=" + currBytes + ",fileName=" + fileName + ",appName=" + appName);
                        //TToast.show(FullScreenVideoActivity.this, "下载暂停，点击下载区域继续", Toast.LENGTH_LONG);
                    }

                    @Override
                    public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
                        Log.d("DML", "onDownloadFailed==totalBytes=" + totalBytes + ",currBytes=" + currBytes + ",fileName=" + fileName + ",appName=" + appName);
                        //TToast.show(FullScreenVideoActivity.this, "下载失败，点击下载区域重新下载", Toast.LENGTH_LONG);
                    }

                    @Override
                    public void onDownloadFinished(long totalBytes, String fileName, String appName) {
                        Log.d("DML", "onDownloadFinished==totalBytes=" + totalBytes + ",fileName=" + fileName + ",appName=" + appName);
                        // TToast.show(FullScreenVideoActivity.this, "下载完成，点击下载区域重新下载", Toast.LENGTH_LONG);
                    }

                    @Override
                    public void onInstalled(String fileName, String appName) {
                        Log.d("DML", "onInstalled==" + ",fileName=" + fileName + ",appName=" + appName);
                        //TToast.show(FullScreenVideoActivity.this, "安装完成，点击下载区域打开", Toast.LENGTH_LONG);
                    }
                });
            }

            @Override
            public void onFullScreenVideoCached() {

            }

            @Override
            public void onFullScreenVideoCached(TTFullScreenVideoAd ad) {
                Log.e(TAG, "Callback --> onFullScreenVideoCachedsuccess");
                mIsLoaded = true;
                //TToast.show(FullScreenVideoActivity.this, "FullVideoAd video cached");
                //ad.showFullScreenVideoAd(FullScreenVideoActivity.this, TTAdConstant.RitScenes.GAME_GIFT_BONUS, null);

            }
        });


    }

    public void showNewInterAd() {
        Log.e("ss", "onLoadFailureListener:==ylh转csj333" + "  mttFullVideoAd===" + mttFullVideoAd + "  mIsLoaded" + mIsLoaded);
        if (mttFullVideoAd != null && mIsLoaded) {
            //step6:在获取到广告后展示
            //该方法直接展示广告
            //mttFullVideoAd.showFullScreenVideoAd(FullScreenVideoActivity.this);
            //展示广告，并传入广告展示的场景
            mttFullVideoAd.showFullScreenVideoAd((Activity) mContext, TTAdConstant.RitScenes.GAME_GIFT_BONUS, null);
            mttFullVideoAd = null;
        } else {
            startRoll();
            loadAd();
        }
    }

    private void startRoll() {
        handlerLooper.removeCallbacksAndMessages(null);
        handlerLooper.sendEmptyMessageDelayed(0, 100);
    }

    Handler handlerLooper = new Handler() {
        public void handleMessage(Message msg) {
            if (mttFullVideoAd != null && mIsLoaded) {//广告展示检查1：广告成功加载，此处也可以使用videoCached来实现视频预加载完成后再展示激励视频广告的逻辑
                handlerLooper.removeCallbacksAndMessages(null);
                mttFullVideoAd.showFullScreenVideoAd((Activity) mContext, TTAdConstant.RitScenes.GAME_GIFT_BONUS, null);
                mttFullVideoAd = null;
            } else {
                handlerLooper.sendEmptyMessageDelayed(0, 100);
            }
        }
    };

    public interface OnItemAllClickListener {
        void onItemAllClickListener();
    }

    public void setItemAllClickListener(OnItemAllClickListener onItemAllClickListener) {
        this.onItemAllClickListener = onItemAllClickListener;
    }


    public interface OnItemCompleteListener {
        void onItemCompleteListener();
    }

    public void setItemCompleteListener(OnItemCompleteListener onItemCompleteListener) {
        this.onItemAllCompleteListener = onItemCompleteListener;
    }


    public interface OnLoadFailureListener {
        void onLoadFailureListener();
    }

    public void setLoadFailureListener(OnLoadFailureListener onLoadFailureListener) {
        this.onLoadFailureListener = onLoadFailureListener;
    }

}
